package com.share.zabbix.request;

import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

public class ZabbixRequestBuilder {
	private static final AtomicInteger nextId = new AtomicInteger(1);

	private ZabbixRequest request = new ZabbixRequest();

	private ZabbixRequestBuilder() {

	}

	static public ZabbixRequestBuilder newBuilder() {
		return new ZabbixRequestBuilder();
	}

	public ZabbixRequest build() {
		if (request.getId() == null) {
			request.setId(nextId.getAndIncrement());
		}
		return request;
	}

	public ZabbixRequestBuilder version(String version) {
		request.setJsonrpc(version);
		return this;
	}

	public ZabbixRequestBuilder paramEntry(String key, Object value) {
		request.putParam(key, value);
		return this;
	}

	public ZabbixRequestBuilder timeFrom(Date fromDate) {
		request.putParam("time_from", fromDate.getTime() / 1000);
		return this;
	}

	public ZabbixRequestBuilder timeTill(Date tillDate) {
		request.putParam("time_till", tillDate.getTime() / 1000);
		return this;
	}

	public ZabbixRequestBuilder filterEntry(String key, Object value) {
		Map<String, Object> filterMap = (Map<String, Object>) request.getParams().get("filter");
		if (filterMap == null)
			filterMap = new HashMap<>();
		filterMap.put(key, value);
		request.putParam("filter", filterMap);
		return this;
	}

	/**
	 * Do not necessary to call this method.If don not set id, ZabbixApi will auto
	 * set request auth..
	 *
	 * @param auth
	 * @return
	 */
	public ZabbixRequestBuilder auth(String auth) {
		request.setAuth(auth);
		return this;
	}

	public ZabbixRequestBuilder method(String method) {
		request.setMethod(method);
		return this;
	}

	public ZabbixRequestBuilder limitGet(int limit) {
		request.putParam("limit", limit);
		return this;
	}

	public ZabbixRequestBuilder extendOutput() {
		request.putParam("output", "extend");
		return this;
	}

	public ZabbixRequestBuilder sortByAsc(String field) {
		request.putParam("sortfield", field);
		request.putParam("sortorder", "ASC");
		return this;
	}

	public ZabbixRequestBuilder sortByDesc(String... fields) {
		request.putParam("sortfield", Arrays.asList(fields));
		request.putParam("sortorder", "DESC");
		return this;
	}

	/**
	 * Do not necessary to call this method.If don not set id, RequestBuilder will
	 * auto generate.
	 *
	 * @param id
	 * @return
	 */
	public ZabbixRequestBuilder id(Integer id) {
		request.setId(id);
		return this;
	}

}
